﻿using OrderStateMachineWebApi_V2.Models;
using OrderStateMachineWebApi_V2.Services;

namespace OrderStateMachineWebApi_V2.ServicesImpl
{
    public class OrderService : IOrderService
    {
        private readonly Dictionary<string, Order> _orders = new();
        private readonly object _lock = new();

        public Order CreateOrder()
        {
            var order = new Order(Guid.NewGuid().ToString());

            lock (_lock)
            {
                _orders[order.Id] = order;
            }

            return order;
        }

        public Order? GetOrder(string orderId)
        {
            lock (_lock)
            {
                return _orders.TryGetValue(orderId, out var order) ? order : null;
            }
        }

        public IEnumerable<Order> GetAllOrders()
        {
            lock (_lock)
            {
                return _orders.Values.ToList();
            }
        }

        public bool ProcessOrder(string orderId, OrderAction action)
        {
            lock (_lock)
            {
                if (!_orders.TryGetValue(orderId, out var order))
                    return false;

                return order.State.ProcessAction(action);
            }
        }
    }
}
